package com.ww.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.jsp.jstl.sql.Result;

public class DB_WEB {
	private String Driver = "com.mysql.jdbc.Driver";
	private String Url = "jdbc:mysql://localhost:3306/wwjd?use-icode=true&characterEncoding=utf-8&autoReconnect=true";
	// private String Url =
	// "jdbc:mysql://localhost:3306/wxdt?use-icode=true&characterEncoding=utf-8&autoReconnect=true";
	private String name = "wwjd";
	private String pwd = "bjwwjd";
	// private String pwd = "mysql";
	private PreparedStatement ps = null;
	private ResultSet rs = null;
	private Result res = null;

	private Connection getConnection() {
		Connection conn = null;
		try {
			Class.forName(Driver);
			conn = DriverManager.getConnection(Url, name, pwd);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return conn;
	}

	public List<Map> ExecuteSql(String sql) {
		System.out.println("ExecuteSql:" + sql);
		rs = null;
		List list = new ArrayList();
		Connection conn = null;
		try {

			conn = this.getConnection();
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();

			while (rs.next()) {
				ResultSetMetaData resultSetMetaData = rs.getMetaData();

				int iCount = resultSetMetaData.getColumnCount();

				String[] columnsName = new String[iCount];
				Map map = new HashMap();

				for (int i = 0; i < iCount; i++) {
					String columnName = resultSetMetaData.getColumnName(i + 1);

					columnsName[i] = columnName;

					Object columnValue = rs.getObject(columnsName[i]);

					if (columnValue == null) {
						map.put(columnsName[i], null);
					}
					if (columnValue instanceof Object) {
						Object columnValue_temp = (Object) columnValue;
						map.put(columnsName[i], columnValue_temp);
					}

				}

				list.add(map);

			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			this.CloseAll(res, conn, ps);
		}
		return list;

	}

	public boolean UpdateSql(String sql) {
		Result res = null;
		Connection conn = null;
		try {
			System.out.println("更新语句:" + sql);
			conn = this.getConnection();
			PreparedStatement ps = conn.prepareStatement(sql);
			if (ps.executeUpdate() > 0) {
				return true;
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			this.CloseAll(res, conn, ps);
		}
		return false;
	}

	private void CloseAll(Result res, Connection conn, PreparedStatement ps) {
		try {
			if (rs != null)
				rs.close();
			if (ps != null)
				ps.close();
			if (conn != null)
				conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public static void main(String[] args) {
		String sql = "SELECT * FROM tb_hello";
		List<Map> list = new DB_WEB().ExecuteSql(sql);
		System.out.println(list.get(0).get("test"));
	}

}
